<?php
namespace app\api\controller\payment;
use app\api\model\order\OrderPayModel;
use think\facade\Db;
use think\Request;
use app\api\server\payment\Notify as NotifyServer;
use app\api\server\payment\NotifyAuction as NotifyAuctionServer;
use think\facade\Log;
use app\api\common;
/**
 * @title 回调类和前端不相关
 */
class Notify
{
    public $get;
    public $type;
    public $total_fee;
    public $REQUEST;
    protected $transaction_id;
    function index(Request $request){
        $_GET=$request->param();
        $this->REQUEST=$request;
        error_reporting(0);
        define('IN_MOBILE', true);
        $input = file_get_contents('php://input');
        Log::record($input,'notify');
        libxml_disable_entity_loader(true);

        if (!empty($input) && empty($_GET['out_trade_no'])) {
            $obj = simplexml_load_string($input, 'SimpleXMLElement', LIBXML_NOCDATA);
            $data = json_decode(json_encode($obj), true);
            if (empty($data)) {
                exit('fail');
            }
            if (empty($data['version']) && ($data['result_code'] != 'SUCCESS' || $data['return_code'] != 'SUCCESS')) {
                $result = array('return_code' => 'FAIL', 'return_msg' => empty($data['return_msg']) ? $data['err_code_des'] : $data['return_msg']);
                echo array2xml($result);
                exit();
            }
            if (!empty($data['version']) && ($data['result_code'] != '0' || $data['status'] != '0')) {
                exit('fail');
            }
            $get = $data;
        }
        else {
            $get = $_GET;
        }
        $this->transaction_id=$get['transaction_id'];//微信订单号用于退款
        $this->get = $get;
        $strs = $this->get['attach'];
        $this->type = $strs;
        $this->total_fee = round($this->get['total_fee'] / 100, 2);
        $this->init();
        exit('fail');
    }
    public function init()
    {
    	//影映品订单
        if($this->type=='10'){
        	$_flag=$this->PayNotify();
        }
        if($this->type=='20'){
        	$_flag=$this->OrderOpusPayNotify();
        }
        if($this->type=='30')
        {
        	$_flag=$this->payMargin();
        }
        if($this->type=='40')
        {
        	$_flag=$this->payAuctionOrder();
        }
        if($_flag==false){
        	$this->fail();
        }else{
        	$this->success();
        }
    }
    public function payAuctionOrder(){
    	$_notify_server=new NotifyAuctionServer();
    	$ordersn = $tid = $this->get['out_trade_no'];
        $order=Db::name("auction_core_pay")->where("ordersn",$ordersn)->find();
        if (!empty($order) && ($order['status'] == '0')) {
        	$order['transaction_id']=$this->transaction_id;
            $_flag=$_notify_server->paymentOrder($order);
            return $_flag;
        }
    
    }
    
    public function payMargin(){
    	$_notify_server=new NotifyAuctionServer();
    	$ordersn = $tid = $this->get['out_trade_no'];
        $order=Db::name("auction_core_pay")->where("ordersn",$ordersn)->find();
        if (!empty($order) && ($order['status'] == '0')) {
        	$order['transaction_id']=$this->transaction_id;
            $_flag=$_notify_server->payment($order);
            return $_flag;
        }
    }
    public function PayNotify(){
    	$_notify_server=new NotifyServer();
    	$ordersn = $tid = $this->get['out_trade_no'];
        $order=Db::name("shadow_core_pay")->where("ordersn",$ordersn)->find();
      
        if (!empty($order) && ($order['status'] == '0')) {
        	$order['transaction_id']=$this->transaction_id;
            $_flag=$_notify_server->payment($order);
            return $_flag;
        }
    }
    
    public function insertFinancial($_order){
    	$_data=[
    		'merch_id'=>$_order['merch_id'],
    		'ordersn'=>$_order['ordersn'],
    		'money'=>'-'.$_order['realprice'],
    		'type_id'=>3,
    		'status_type'=>2,
    		'order_id'=>$_order['id'],
    		'create_time'=>time()
    	];
    	$_user=Db::name("user")->where(['wxapp_openid'=>$_order['wxapp_openid']])->field("*")->find();
    	$_data['user_id']=$_user['id'];
    	$_financial_obj=new FinancialModel();    	
    	$_flag=$_financial_obj->insertFinancial($_data);
    	if(!$_flag){
    		Log::record(__function__.":".__line__."\r\n"."parceNotify存储资金记录失败");
    		Log::record(__function__.":".__line__."\r\n"."insert:".json_encode($_data));
    		return false;
    	}
    	return true;
    }
    function OrderOpusPayNotify(){
        $_notify_server=new NotifyServer();
        $order=(new OrderPayModel())->getFind('ordersn',$this->get['out_trade_no']);
        if (!empty($order) && ($order['status'] == 0)) {
            $order->transaction_id=$this->transaction_id;
            $_flag=$_notify_server->paymentOrderOpus($order);
            return $_flag;
        }
    }
    public function success()
    {
        $result = array('return_code' => 'SUCCESS', 'return_msg' => 'OK');
        echo $this->array2xml($result);
        exit();
    }

    public function fail()
    {
        $result = array('return_code' => 'FAIL', 'return_msg' => '签名失败');
        echo $this->array2xml($result);
        exit();
    }
    
    public function array2xml($data){
	  $xml = "<xml>";
        foreach ($data as $key=>$val)
        {
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
}
}